<?php
/*

  Copyright 2005  Blackhacker (email : bh@blackhacker.net)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

class BH_Tags {

	// retrieve tag values from post_meta
	function get_post_tags() {
		$tags = get_post_custom_values('tags');

		if(!empty($tags[0]))
			$tags_array = explode(' ', $tags[0]);

		return($tags_array); // return an array of tags
	}


	function tag_link( $tag, $url, $text='' ) {
		if (!$text) $text = $tag;
		return '<a href="'. $url . urlencode(urldecode($tag)) .'" rel="tag">'. urldecode($text) .'</a>';
	}


	function get_post_tag_links($before_each, $between_each, $after_each, $url) {
		$tags_array = self::get_post_tags();

		if (empty($tags_array)) return '';

		$list = '';
		
		foreach ($tags_array as $tag) {
			if ($list) {
				$list .= $between_each;
			}

			$list .= $before_each;
			$list .= self::tag_link($tag, $url);
			$list .= $after_each;
		}

		return($list);
	}

	function get_related_tag_links($before_each, $between_each, $after_each, $url, $related = '') {

		$tags_array = self::get_tags_count(0,$related ? $related : get_query_var("tag") );

		 if (empty($tags_array)) return '';

		$list = '';
		foreach ($tags_array as $tag => $freq) {
			if ($list) {
				$list .= $between_each;
			}

			$list .= $before_each;
			$list .= BH_Tags::tag_link($tag, $url, "$tag($freq)");
			$list .= $after_each;

		}

		return($list);
	}

	function get_tags_count($limit=0, $related_to='') {
		global $wpdb;

		if ($related_to)
			$related_to = urlencode($related_to);

		$q ="SELECT meta_value";
		$q .=" FROM ". $wpdb->postmeta ." pm, ". $wpdb->posts ." p";
		$q .=" WHERE pm.post_id=p.id and";
		$q .=" p.post_status in ('publish') and";
		//$q .=" p.post_status not in ('draft', 'private') and";
		$q .=" pm.meta_key='tags'";

		if ($related_to)
			$q .= " and pm.meta_value like '%". $related_to ."%'";

		if ($limit) {
			$q .=" order by p.post_date desc";
			$q .= " limit $limit";
		}

		$result = $wpdb->get_col($q);
		$tags = $result ? explode(" ", trim(implode(' ', $result))) : array();

		if ($related_to){
			$x = array();
			foreach ($tags as $tag)
				if (strcasecmp($related_to, $tag) != 0)
					array_push($x, $tag);

			$tags =$x;
		}

		usort($tags, strcasecmp);

		return array_count_values($tags);
	}

	/*
	Code adapted from the the 'Word Press Heat Map' http://www.engadgeted.net/projects/wordpress-heat-map-plugin/
	*/
	function cloud($smallest=12, $largest=48, $before='', $after=' ', $min_freq=1, $limit=0) {
		global $querystring_start, $querystring_equal, $querystring_separator, $wpdb;

		$tags = BH_Tags::get_tags_count($limit);

		$min = ($min = min($tags)) < $min_freq ? $min_freq : $min;
		$max = max($tags);
		$spread = $max - $min;

		if ($largest != $smallest) {
			$fontspread = $largest - $smallest;
			if ($spread != 0) {
				$fontstep = $fontspread / $spread;
			} else {
				$fontstep = 0;
			}
		}
		
		$output ='cloud';

		foreach ($tags as $tag => $freq) {

			if ($freq < $min_freq)
				continue;

			$url = "/tag/". $tag;
			$fraction = ($freq - $min);
			$fontsize = $smallest + ($fontstep * $fraction);

			$style = "";

			if ($largest != $smallest) {
				$style = "font-size:".round($fontsize)."px;";
			}

			$tag = str_replace("+", " ", $tag);

			if ($limit)
				$l = " in the last $limit posts";
				
			if ($output) $output .= ' ';

			$output .= "<a href=\"$url\" title=\"$freq posts with '$tag' tag". $l ."\" style=\"$style\" >$tag</a>";
		}
		
		echo $output;
	}

	/* plugin API implementation */

	function the_content($content) {
		//if (!is_feed()) return $content;
		return $content . '<p class="tags">Tags: '. BH_Tags::get_post_tag_links('',', ', '', get_bloginfo('url') .'/tag/') .'</p>';

	}

	// output textarea to easily add tags in admin menu (addition to the post form)
	function simple_edit_form() {
		$tags = get_post_meta($_REQUEST['post'], 'tags', true);
		echo '<fieldset id="posttags"><legend><a href="http://technorati.com/help/tags.html" title="Information about Technorati tags.">' . __('Tags', 'BH Tags') . '</a></legend>';
		echo '<div><input type="text" name="tags" id="tags" size="95" value="' . $tags . '" /><br />' . __('Separate tags with spaces', 'BH Tags') . '</div></fieldset>';
	}

	// general custom field update function
	function edit_post($id) {
		$setting = $_POST['tags'];
		$meta_exists = update_post_meta($id, 'tags', $setting);
		if(!$meta_exists) {
			add_post_meta($id, 'tags', $setting);
		}
	}

	function rewrite_rules($rules) {
		global $wp_rewrite;

		$newrule['tag/(.+)?$']="index.php?tag=\$matches[1]";
		return ($rules + $newrule);
	}

	function query_vars($vars) {
		$vars[] = 'tag';
		return $vars;
	}

	function parse_query() {
		/* adapted from jeromes keywords http://svn.wp-plugins.org/jeromes-keywords/tags/release-1.3/jeromes-keywords.php */
		if (!is_tag()) return;

		global $wp_query;
		$wp_query->is_single = false;
		$wp_query->is_page = false;
		$wp_query->is_archive = true;
		$wp_query->is_search = false;
		$wp_query->is_home = false;

		add_filter('posts_where', array('BH_Tags', 'posts_where'));
		add_action('template_redirect', array('BH_Tags', 'template_redirect'));
	}

	function template_redirect() {

		if (!is_tag())  return;

		if ( file_exists(TEMPLATEPATH . "/tag.php") ) {
			include(TEMPLATEPATH . "/tag.php");
			exit;
		}
	}

	function posts_where($where) {
		global $wpdb;

		if (!is_tag()) return $where;

		$tag = str_replace(" ", "\\\\+", get_query_var('tag'));
		$sql = "select distinct post_id from ". $wpdb->postmeta . " where meta_key='tags' and meta_value regexp '[^+]?[[:<:]]". $tag ."[[:>:]][^+]?'";
		$post_ids = $wpdb->get_col($sql);

		if ($post_ids) {
			if($where)
				$where .=' and ';

			$where .= ' ID in (' . join(',', $post_ids) .')';
		}

		return $where;
	}

	/* function plugins_loaded() {
		if (!function_exists('register_sidebar_widget') || !function_exists('register_widget_control'))
			return;

		register_sidebar_widget('BH Related Tags', array('BH_Tags','related_widget'));
		register_widget_control('BH Related Tags', array('BH_Tags','related_control'), 300, 100);
		register_sidebar_widget('BH Tag Cloud', array('BH_Tags','cloud_widget'));
		register_widget_control('BH Tag Cloud', array('BH_Tags','cloud_control'), 300, 100);
	}*/

}

?>
